package com.longe.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longe.common.FileDfsUtil;
import com.longe.common.Result;
import com.longe.dao.UserMapper;
import com.longe.entity.User;
import com.longe.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author longe
 * @since 2020-05-23
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${password.sign}")
    private String sign;

    @Value("${qrcode.dir}")
    private String qrCodeDir;

    @Autowired
    private FileDfsUtil fileDfsUtil;

    @Override
    public Result<Object> register(User user) {
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getUsername, user.getUsername());
        User existUser = this.getOne(query);
        if(null != existUser){
            return new Result(false, "该账号已存在", null);
        }
        user.setPassword(MD5.create().digestHex(user.getPassword() + sign))
                .setCreateTime(new Date());

        //生成二维码
        // 生成指定url对应的二维码到文件，宽和高都是300像素
        String filePath = qrCodeDir + user.getUsername() + ".jpg";
        QrCodeUtil.generate(user.getUsername(), 300, 300, FileUtil.file(filePath));

        File file = new File(filePath);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), user.getUsername() + ".jpg", null, inputStream);
            List<String> qrCode = fileDfsUtil.uploadFile(multipartFile);
            user.setQrCode(qrCode.get(0));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, " 生成二维码失败", null);
        }

        this.save(user);
        return new Result(true, "注册成功", null);
    }

    @Override
    public Result<User> login(User user) {
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, MD5.create().digestHex(user.getPassword() + sign));
        user = this.getOne(query);
        if(null == user){
            return new Result(false, "账号或密码错误", null);
        }
        user.setPassword(null);
        return new Result(true, "登录成功", user);
    }

    @Override
    public Result<User> upload(MultipartFile file, Integer userId) {

        List<String> result = fileDfsUtil.uploadFile(file);
        if(null == result || result.size() < 1){
            new Result(false, "上传头像失败", null);
        }

        User updateUser = new User();
        updateUser.setId(userId).setPicNormal(result.get(0)).setPicSmall(result.get(1));
        boolean bool = this.updateById(updateUser);
        if(!bool){
            new Result(false, "上传头像失败", null);
        }

        User user = this.getById(userId);
        user.setPassword(null);
        return new Result(true, "上传成功", user);
    }

    @Override
    public Result<User> updateNickname(User user) {
        User updateUser = new User();
        updateUser.setId(user.getId()).setNickname(user.getNickname());
        boolean bool = this.updateById(updateUser);
        if(!bool){
            new Result(false, "更改昵称失败", null);
        }
        user = this.getById(user.getId());
        user.setPassword(null);
        return new Result(true, "更改昵称成功", user);
    }

    @Override
    public Result<User> findByUsername(User user) {

        LambdaQueryWrapper<User> query = new LambdaQueryWrapper();
        query.eq(User::getUsername, user.getUsername());

        user = this.getOne(query);
        if(user == null){
            return new Result(false, "该账号不存在", null);
        }
        return new Result(true, "", user);
    }

}
